package com.yc.myspringboot.transaction;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.yc.myspringboot.mapper.DemoMapper;
import com.yc.myspringboot.po.DemoPo;

@Service
public class C1 {

	@Autowired
	private TransactionTemplate transactionTemplate;
	
	@Autowired
	private DemoMapper demoMapper;
	
	/**
	 * 细粒度控制事务
	 * 参考文章：https://blog.csdn.net/qq_20009015/article/details/84863295
	 */
	@SuppressWarnings("unchecked")
	public void m1() {
		DemoPo newData1 = new DemoPo(null, 11, "zhangsan1", new Date(), "");
		DemoPo newData2 = new DemoPo(null, 12, "zhangsan2", new Date(), "");
		DemoPo newData3 = new DemoPo(null, 13, "zhangsan3", new Date(), "");
		//插入第一条数据
		demoMapper.insert(newData1);//预期：无事务，无法插入 ——>  实际：可以插入
		
		//事务内报错
		transactionTemplate.execute(new TransactionCallback() {

			@Override
			public Object doInTransaction(TransactionStatus status) {
				demoMapper.insert(newData2);//预期：有事务，可以插入
				demoMapper.insert(newData3);//预期：有事务，可以插入
				throw new RuntimeException();
			}
			
		});
		
		//事务内正常不报错
		//TransactionCallback 中的doInTransaction是个函数式接口，可以写成lambda表达式
//		transactionTemplate.execute((status) -> {
//			demoMapper.insert(newData2);//预期：有事务，可以插入，报错后，插入失败
//			demoMapper.insert(newData3);//预期：有事务，可以插入，报错后，插入失败
//			return null;
//		});
		
	}
	
}
